import json
from venv import logger
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions
from ..models import Bot, Conversation, BotPublishHistory
from ..serializers import BotSerializer, ConversationSerializer
import requests  # type: ignore
from django.conf import settings  # 引入 settings

from ..services.prompt_service import PromptGenerationService
from .BaseResponse import BaseResponse

class BotPublishView(APIView):
    permission_classes = [permissions.IsAuthenticated]  # 确保用户已登录

    def post(self, request):
        # 获取 Coze 平台的令牌（从环境变量中获取）
        coze_access_token = settings.COZE_ACCESS_TOKEN
        if not coze_access_token:
            return BaseResponse.error("Missing Coze access token", status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 获取请求数据
        bot_id = request.data.get("bot_id")
        connector_ids = request.data.get("connector_ids")

        # 检查必填字段
        if not bot_id or not connector_ids:
            return BaseResponse.error("Missing required parameters: bot_id, connector_ids")

        # 确保智能体属于当前用户
        try:
            bot = Bot.objects.get(bot_id=bot_id, user=request.user)
        except Bot.DoesNotExist:
            return BaseResponse.error("Bot not found", status=status.HTTP_404_NOT_FOUND)

        # 调用 Coze API 发布智能体
        url = "https://api.coze.cn/v1/bot/publish"
        headers = {
            "Authorization": f"Bearer {coze_access_token}",
            "Content-Type": "application/json"
        }
        data = {
            "bot_id": bot.bot_id,
            "connector_ids": connector_ids,
        }

        response = requests.post(url, json=data, headers=headers)

        if response.status_code == 200:
            # 解析返回数据
            api_response = response.json()
            if api_response.get("code") == 0:
                # 保存发布历史
                publish_history = BotPublishHistory(
                    bot=bot,
                    connector_ids=connector_ids,
                )
                publish_history.save()

                return BaseResponse.success(api_response)
            else:
                # API 调用失败
                return BaseResponse.error(api_response.get("msg"))
        else:
            # 请求失败
            return BaseResponse.error("Failed to publish bot", status=status.HTTP_500_INTERNAL_SERVER_ERROR)